﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LongestSequence.Question;

namespace LongestSequence.Answer
{
    class Albin: ILongestSequence
    {
        public struct Num
        {
            public int be;
            public int zero;
        }
        public int GetLongestSequence(int[] Array)
        {
            int length = Array.Length;
            int count = 1;
            Num[,] arr = new Num[length, length];
            for (int i = 0; i < length; i++)
            {
                if (Array[i] == 0)
                {
                    arr[i, i].zero = 0;
                    for (int j = i + 1; j < length; j++)
                    {
                        if (Array[j] == 0)
                        {
                            arr[i, j].zero = arr[i, j - 1].zero + 1;
                            continue;
                        }
                        else
                        {
                            arr[i, j].zero = arr[i, j - 1].zero;
                        }
                    }
                }
                else
                {
                    for (int j = i + 1; j < length; j++)
                    {
                        if (Array[j] == 0)
                        {
                            arr[i, j].zero = arr[i, j - 1].zero + 1;
                            arr[i, j].be = arr[i, j - 1].be;
                            continue;
                        }
                        else
                        {
                            if (Math.Abs(Array[i] - Array[j]) < arr[i, j - 1].be)
                            {
                                arr[i, j].be = arr[i, j - 1].be;
                            }
                            else
                            {
                                arr[i, j].be = Math.Abs(Array[i] - Array[j]);
                            }
                            arr[i, j].zero = arr[i, j - 1].zero;
                        }
                    }
                }
            }
            for (int i = 0; i < length; i++)
            {
                for (int j = i + 1; j < length; j++)
                {
                    if (j - i == arr[i, j].be + arr[i, j].zero)
                    {
                        if (j - i + 1 > count)
                        {
                            count = j - i + 1;
                        }
                    }
                }
 
            }            
            return count ;
        }
    }
}
